package sq.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sq.dao.Food;
import sq.dao.FoodType;
import sq.dao.User;
import sq.repository.FoodRepository;
import sq.repository.FoodTypeRepository;
import sq.repository.UserRepository;
import sq.service.FoodService;
import sq.util.PartUtils;
import sq.util.QiniuUploadService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;


/**
 * 文件上传接口实现类
 * sunquan
 */

@Service
public class FoodServiceImpl implements FoodService {
    private static Logger logger = LoggerFactory.getLogger(FoodServiceImpl.class);
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private FoodRepository foodRepository;
    @Autowired
    private FoodTypeRepository foodTypeRepository;
    @Autowired
    private QiniuUploadService qiniuUploadService;

    @Override
    public List<FoodType> findAll() {
        return foodTypeRepository.findAll();
    }

    @Override
    public List<Food> findAllFood() {
        return foodRepository.findAll();
    }


    @Override
    public String foodUpload(Food food, MultipartFile file, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userName = session.getAttribute("userSession").toString();
        User user = userRepository.findUserByUsername(userName);
        String phone = user.getPhone();
        File dest = new File("C:" + File.separator + File.separator + phone + File.separator + file.getOriginalFilename());
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String mimeType = "";
        String originalName=file.getOriginalFilename();
        try {
            mimeType = originalName.substring(originalName.lastIndexOf('.'));
        } catch (NullPointerException e) {
            logger.info("空指针异常", e);
        }
        if(!mimeType.equalsIgnoreCase(".jpg")&&!mimeType.equalsIgnoreCase(".png")){
            return "2";
        }
        String flag = qiniuUploadService.QiniuUpload(dest.getAbsolutePath());
        if (dest.getParentFile().exists()) { //判断文件父目录是否存在
            PartUtils.deleteAllFilesOfDir(dest.getParentFile());
        }
        if (flag != "false") {
            Food newFood = new Food();
            newFood.setFoodName(food.getFoodName());
            newFood.setFoodType(food.getFoodType());
            newFood.setCalorie(food.getCalorie());
            newFood.setRemarks(food.getRemarks());
            newFood.setFoodImg(flag);
            newFood.setOriginalName(file.getOriginalFilename());
            newFood.setUpdateTime(new Date());
            newFood.setPrice(food.getPrice());
            foodRepository.save(newFood);
            FoodType foodType = foodTypeRepository.findFoodTypeByTypeId(food.getFoodType());
            foodType.setTypeNumber(foodType.getTypeNumber() + 1);
            foodTypeRepository.save(foodType);
            return "0";        //上传成功
        } else {

            return "1";           //上传失败
        }
    };

    @Override
    @Transactional
    public void deletFood(int foodId) {
        foodRepository.delete(foodId);
    }

    @Override
    public Food queryFood(int foodId) {

        return foodRepository.getOne(foodId);
    }

    @Override
    public void updateFood(Food food) {
        foodRepository.updateFoodByFoodId(
                food.getFoodName(),
                food.getFoodType(),
                food.getPrice(),
                food.getCalorie(),
                food.getRemarks(),
                food.getFoodId(),
                new Date()
        );
    }

    @Override
    public FoodType addType(FoodType foodType) {
        foodType.setTypeNumber(0);
        FoodType newType = foodTypeRepository.save(foodType);
        return newType;
    }

    @Override
    public List<Food> findSearchFood(int foodType,String foodName) {
        List<Food> food=null;
        if(foodType==0){
             food= foodRepository.findFoodByFoodNameLike("%"+foodName+"%");
        }
        else{
             food= foodRepository.findFoodByFoodTypeAndAndFoodNameLike(foodType,"%"+foodName+"%");
        }

        return food;
    }


}
